﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XWord.Fundamental.Domain;
using Caliburn.PresentationFramework.ApplicationModel;
using System.Windows.Data;
using Caliburn.Core.Metadata;
using XWord.Common;
using Caliburn.PresentationFramework.Metadata;
using System.Windows;
using Microsoft.Practices.ServiceLocation;
using XWord.Fundamental.Domain.Model;
using XWord.Fundamental.Domain.Services;
using XWord.GUI.Presenters.Interface;

namespace XWord.GUI.Presenters
{
    public interface IMasterScreen<T> : IPresenter
    {
        ICollection<T> EntityList { get; set; }

        IModel<T> Model { get; set; }
    }


    public class DetailScreen<T> : Presenter
    {

        private IServiceLocator _entityFactory;

        public DetailScreen(IServiceLocator entityFactory)
        {
            _entityFactory = entityFactory;

        }

        private string originName;

        private T _entity;
        public T Entity
        {
            get
            {
                return _entity;
            }
            set
            {
                _entity = value;
                originName = (value as Entity).Name;
            }
        }

        private IEditingObjectAdapter _editingObjectAdapter;

        private IMasterScreen<T> ParentScreen
        {
            get
            {
                return this.Parent as IMasterScreen<T>;
            }
        }

        public T InitializeNewEntity()
        {
            this.Entity = _entityFactory.GetInstance<T>();
            _editingObjectAdapter = new EditingObjectAdapter(Entity as IEditingObject);
            _editingObjectAdapter.BeginNewEdit();
            return Entity;
        }

        public bool IsEdit { get; set; }

        public void InitializeEditEntity()
        {
            _editingObjectAdapter = new EditingObjectAdapter(Entity as IEditingObject);
            _editingObjectAdapter.BeginEdit();
        }

        public void Save()
        {
            //if (_editingObjectAdapter.EditObj.IsNew)
            //    ParentScreen.EntityList.Add(Entity);
            //ParentScreen.Model.Save(Entity);
            //_editingObjectAdapter.EndEdit();
            //RemotingServiceFactory.GetWordService().SaveEtymaLibrary(originName, Entity as EtymaLibrary, 1);

            CloseWindow();
        }

        public void Cancel()
        {
            //_editingObjectAdapter.CancelEdit();
            CloseWindow();
        }

        protected void CloseWindow()
        {
            this.Shutdown();
            this.GetView<Window>(null).Close();
        }
    }


    [PerRequest(typeof(EtymaLibraryEditPresenter))]
    public class EtymaLibraryEditPresenter : DetailScreen<EtymaLibrary>
    {
        public EtymaLibraryEditPresenter(IServiceLocator entityFactory)
            : base(entityFactory)
        {
        }
    }
}
